package net.topicopedia.other;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;

@SuppressWarnings("serial")
public class GetAllUserTopicCategoriesCloudServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		

		resp.addHeader("Access-Control-Allow-Origin", "*");
		resp.setContentType("text/plain");
		
		String output = "[";
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    
	    Query categoriesQuery = new Query("Category");
	    PreparedQuery pqCategories = datastore.prepare(categoriesQuery);
	    
	    Query userQuery = new Query("User");
	    PreparedQuery pqUsers = datastore.prepare(userQuery);
	    
	    HashMap<Key, Integer > allUserTopicCategories = new HashMap<Key, Integer>();
	    for (Entity category : pqCategories.asIterable() ) {
	    	Integer count = 0;
	    	
	    	for (Entity user : pqUsers.asIterable() ) {
	    		@SuppressWarnings("unchecked")
				HashMap<Key, Long > userTopicCategories = (HashMap<Key, Long>) user.getProperty( "categories" );
	    		if ( userTopicCategories != null && userTopicCategories.containsKey( category.getKey() ) )
	    		{
	    			Long usercount = (Long) userTopicCategories.get( category.getKey() );
	    			if (  usercount != null && usercount > 0 )
		    		{
		    			count++;
		    		}
	    		}
	    	}
	    	allUserTopicCategories.put( category.getKey(), count );
	    	
	    	if ( output.length() > 2 )
			{
				output += ", " ;
			}
	    
			
			String storedUuid = category.getKey().getId() + "";
			String storedName = (String) category.getProperty("name");
			String storedCount =  count + "";
		  
			output += "{ \"uuid\": \"" + storedUuid + "\", \"name\": \"" + storedName + "\", \"count\": \"" + storedCount + "\"}";
		}
		
		output += "]";
		
		resp.getWriter().println( output );
		
	}
}
 